from django.shortcuts import render, redirect, reverse
from django.http import JsonResponse, HttpResponse, HttpResponseRedirect
from django.views import View
import hashlib
from .models import User, QQUser
import json
from django.conf import settings
from common import utils
from common.py_redis import PyRedis
from django.db.utils import IntegrityError
import time
import  threading
from django.core.mail import send_mail
from common.my_jwt import MyJWT
import requests
import logging
from django.db import transaction
from common import message 


LOGApi = logging.getLogger('api')
# Create your views here.

def register_view(request):
    try:
        if request.method=='GET':
            return render(request,'index/register.html')
        elif request.method=='POST':
            # return utils.Response(result=0,msg="请输入邀请码")
            req_data = json.loads(request.body) 
            username = req_data.get('username')
            pwd = req_data.get('pwd')
            confirm_pwd = req_data.get('c_pwd')
            code = req_data.get('code')
            if pwd != confirm_pwd:
                return utils.Response(result=0)
            else:
                code_key = request.COOKIES.get('code_key')
                if not utils.code(code_key,code):
                    return utils.Response(result=0,msg='验证码错误')
                salt = utils.generate_code_all()
                # 密码和盐进行组合
                pwd_md5 = utils.get_md5(utils.pwd_salt(pwd,salt)) 
                kwargs = {
                    'username':username,
                    'password':pwd_md5,
                    'salt':salt
                }
                user = User.objects.create(**kwargs)
                data = {
                    'username':username
                }
                ip = request.META.get('REMOTE_ADDR')
                threading.Thread(target=message.register_success(username,pwd,ip)).start()
                return utils.Response(data=data)
    except IntegrityError as e:
        return utils.Response(result=0,msg="用户名已存在")
    except Exception as e:
        return utils.Response(result=0,msg=str(e))


def login_view(request):
    if request.method=='GET':
        try:
            if request.username and request.user_id:
                return redirect(reverse('index'))
            else:
                return render(request,'index/login.html')
        except Exception as e:
            LOGApi.error(str(e))
            return render(request,'index/login.html')
    elif request.method == 'POST':
        try:
            req_data = json.loads(request.body)
            username = req_data.get('username')
            pwd = req_data.get('pwd')
            code = req_data.get('code')
            code_key = request.COOKIES.get('code_key')
            if not utils.code(code_key,code):
                return utils.Response(result=0,msg='验证码错误')
            user = User.objects.get(username=username)
            db_salt = user.salt
            pwd_md5 = utils.get_md5(utils.pwd_salt(pwd, db_salt))
            db_pwd_md5 = user.password
            if pwd_md5 == db_pwd_md5:
                # request.cookies['username']=username
                # request.cookies['uid']=user.id
                token_data = {
                    'username':username,
                    'uid':user.id
                }
                jwt_key = settings.JWT_KEY
                my_jwt = MyJWT(jwt_key)
                token = my_jwt.encode(token_data,settings.JWT_TIME)
                data = {
                    'result':1,
                    'data':{
                        'token':token
                    },
                    'msg':"登录成功"
                }
                resp = HttpResponse(json.dumps(data),content_type='application/json')
                resp.set_cookie('token', token)
                resp.set_cookie('username', username)
                resp.set_cookie('uid', user.id)
                resp.set_cookie('figureurl', user.figureurl)
                return resp
            else:
                return utils.Response(result=0,msg="用户名或密码错误")
        except User.DoesNotExist as e:
            return utils.Response(result=0,msg="用户不存在")
        except Exception as e:
            return utils.Response(result=0,msg=str(e))

# 中转站
class QQLogin302(View):
    
    def get(self, request):
        return render(request, 'index/302.html')


# QQ登录
class QQLogin(View):
    def get_access_token(self, code):
        """
        根据code获取access_token
        """
        url = "https://graph.qq.com/oauth2.0/token"
        params = {
            'grant_type':'authorization_code',
            'client_id':settings.QQ_LOGIN_APP_ID,
            'client_secret':settings.QQ_LOGIN_APP_KEY,
            'code':code,
            'redirect_uri':settings.REDIRECT_URI[0],
            'fmt':'json'
        }
        req = requests.get(url,params=params)
        LOGApi.info(req.content)

    def get_open_id(self, access_token):
        # 根据access_token 获取用户信息
        try:
            url = "https://graph.qq.com/oauth2.0/me"
            params = {
                'access_token':access_token,
                'fmt':'json'
            }
            req = requests.get(url,params=params)
            repJson = req.json()
            openid = repJson.get('openid')
            LOGApi.info(str(req.text))
            return openid
        except Exception as e:
            LOGApi.info(str(e))
            return None

    def get_user_info(self,access_token,openid,app_key=settings.QQ_LOGIN_APP_ID):
        # 根据access_token 获取用户信息
        try:
            url = "https://graph.qq.com/user/get_user_info"
            params = {
                'access_token':access_token,
                # 'fmt':'json',
                'oauth_consumer_key':app_key,
                'openid':openid
            }
            req = requests.get(url,params=params)
            repJson = req.json()
            return repJson
        except Exception as e:
            LOGApi.info(str(e))
            return None


    def get(self, request):
        # qqbug 直接返回给access_token 2022年3月8号恢复使用code
        try:
            access_token = request.GET.get('access_token')
            openid = self.get_open_id(access_token)
            if openid:
                qq_user = QQUser.objects.filter(openid=openid).first()
                if not qq_user:
                    user_info_dict = self.get_user_info(access_token,openid)
                    print(user_info_dict)
                    nickname = user_info_dict.get('nickname')
                    LOGApi.info(str(user_info_dict))
                    kwargs = {
                        'figureurl':user_info_dict.get('figureurl'),
                        'nickname':str(nickname),
                        'gender':str(user_info_dict.get('gender')),
                        'openid':openid
                    }
                    salt = utils.generate_code_all()
                    pwd = utils.get_random_pwd()
                    pwd_md5 = utils.get_md5(utils.pwd_salt(pwd,salt)) 
                    user_data = {
                        'username':nickname,
                        'password':pwd_md5,
                        'salt':salt,
                        'age':time.localtime().tm_year-int(user_info_dict.get('year')),
                        'gender':1 if user_info_dict.get('gender_type') == 2 else 0,
                        'figureurl':user_info_dict.get('figureurl'),
                    }
                    with transaction.atomic():
                        user = User.objects.create(**user_data)
                        kwargs['user_id'] = user.id
                        obj = QQUser.objects.create(**kwargs)
                        ip = request.META.get('REMOTE_ADDR')
                        threading.Thread(target=message.qq_register_success(nickname,pwd,ip)).start()
                else:
                    user = User.objects.get(id=qq_user.user_id)
                # 设置token
                token_data = {
                    'username':user.username,
                    'uid':user.id
                }
                my_jwt = MyJWT()
                token = my_jwt.encode(token_data,settings.JWT_TIME)
                # resp = HttpResponseRedirect('/')
                resp = HttpResponse('恭喜您登录成功,正在跳转首页，<script>setTimeout("location=\'/\';",1000);</script>如未跳转您可以点击<a href="/">返回首页</a>')
                resp.set_cookie('token', token)
                resp.set_cookie('username',json.dumps(token_data['username']))
                resp.set_cookie('qq',True)
                resp.set_cookie('figureurl',user.figureurl)
                return resp
            else:
                return render(request,'error/forbid.html',{"forbid_tip":"信息无法获取，登录失败"})
        except User.DoesNotExist as e:
            LOGApi.error(str(e))
            return render(request,'error/forbid.html',{"forbid_tip":"用户异常，请加群联系管理员"})
            return HttpResponse()
        except Exception as e:
            LOGApi.error(str(e))
            return render(request,'error/forbid.html',{"forbid_tip":"网络异常登录失败"})

    def post(self, requets):
        pass















